﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using TaskManager.DataAccess.Modules;
using TaskManager.Domain.Modules;
using TaskManager.Web.Modules;

namespace TaskManager.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(MvcApplication));

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{tab}/{id}", // URL with parameters
                new { controller = "Task", action = "MyTasks", id = UrlParameter.Optional, tab = 0 } // Parameter defaults
            );
        }

        public override void Init()
        {
            BeginRequest += (object sender, EventArgs e) =>
            {
                if (Log.IsDebugEnabled)
                {
                    if (string.IsNullOrEmpty(Request.CurrentExecutionFilePathExtension))
                        Log.Debug("Entering new HTTP request.Resource=[" + Request.RawUrl + "],HTTP method [" + Request.HttpMethod + "]");
                }
            };

            EndRequest += (object sender, EventArgs e) =>
            {
                if (Log.IsDebugEnabled)
                {
                    if (string.IsNullOrEmpty(Request.CurrentExecutionFilePathExtension))
                        Log.Debug("Leaving HTTP request.Resource=[" + Request.RawUrl + "]");
                }
            };
        }

        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();
            
            if (Log.IsInfoEnabled) Log.Info("Starting application");

            AreaRegistration.RegisterAllAreas();

            // Create DI container
            var builder = new ContainerBuilder();

            builder.RegisterModule(new AutofacWebTypesModule());

            // Register application modules
            builder.RegisterModule(new DataAccessLayer());
            builder.RegisterModule(new DomainLayer());
            builder.RegisterModule(new PresentationLayer());

            IContainer container = builder.Build();

            // Setup DI as default MVC controller factory
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            if (Log.IsInfoEnabled) Log.Info("Application successfully started");
        }
    }
}